package com.qu.visitmodel.service;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.czt.mp3recorder.MP3Recorder;
import com.qu.visitmodel.utils.TimeUtil;
import com.qu.visitmodel.event.MessageEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by qu on 2017/7/22.
 */

public class RecordService extends Service {

    public static final String TAG = "MyService";

    private MP3Recorder mRecorder = new MP3Recorder(new File(Environment.getExternalStorageDirectory(),"test2.mp3"));

    private Timer timer;

    private int recorderSecondsElapsed; //录制时间

    @Override
    public void onCreate() {
        super.onCreate();

        try {
            mRecorder.start(); // 开始录制
            EventBus.getDefault().post(MessageEvent.START_STATE);
            startTimer();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.d(TAG, "onCreate() executed");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand() executed");

        return super.onStartCommand(intent, flags, startId);
    }

    private void startTimer(){
        stopTimer();
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                updateTimer();
            }
        }, 0, 1000);
    }

    private void stopTimer(){
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
    }

    private void updateTimer() {
        recorderSecondsElapsed++;
        EventBus.getDefault().post(TimeUtil.formatSeconds(recorderSecondsElapsed)); // 传递录制时间
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mRecorder.stop();

        EventBus.getDefault().post(MessageEvent.STOP_STATE);
        stopTimer();

        Log.d(TAG, "onDestroy() executed");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
